import * as mqtt from "mqtt/dist/mqtt.min";
import { onUnmounted, ref, reactive } from 'vue';
import { ElNotification } from 'element-plus'
import useUserStore from '@/store/modules/user'

export default function useMqtt(pic, bol) {
    let client = ref({
        connected: false
    });
    const notifyPromise = ref(Promise.resolve())
    const qosList = [0, 1, 2];
    // 订阅
    const topic = ref(pic)
    const qos = ref(2)
    // 链接地址
    const hostUrl = ref('101.37.163.199')
    const connection = reactive({
        // 183.92.128.122
        clean: true,
        clientId: "IOT_Platform_" + Math.random().toString(16).substring(2, 8),
        connectTimeout: 30 * 1000, // ms,
        host: "183.92.128.122",
        password: "Sgj808606",
        port: 8083,
        endpoint: "/mqtt",
        protocol: "ws",
        reconnectPeriod: 4000, // ms
        username: "pureut",
    });
    const messageValue = ref(false)
    // 订阅的信息
    const receiveNews = ref('')
    const time = ref(null)
    const startMqtt = () => {
        try {
            const { protocol, host, port, endpoint, ...options } = connection

            const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
            client.value = mqtt.connect(connectUrl, options);
            if (client.value.on) {
                // 连接
                client.value.on("connect", () => {
                    console.log("连接成功 successful");
                    // if (bol) {
                    link()
                    // } else {
                    // UnSubscribe()
                    // }

                });
                // 重连
                client.value.on("reconnect", handleOnReConnect);
                client.value.on("error", (error) => {
                    console.log("重连失败 error:", error);
                });
                // 收到信息
                client.value.on("message", (topic, message) => {
                    // receiveNews.value = receiveNews.value.concat(message.toString());
                    let phaseValue = JSON.parse(message)
                    // phaseValue.forEach((value, index, array) => {
                    //     notifyPromise.value = notifyPromise.value.then(() => {
                    //         ElNotification({
                    //             type: 'warning',
                    //             title: '警告',
                    //             message: value.msg,
                    //             position: 'bottom-right',
                    //             offset: 10
                    //         })
                    //     })
                    // })
                    // console.log(sessionStorage.getItem('topic'), topic, '监听');
                    if (sessionStorage.getItem('topic') == topic) {
                        // console.log(`收到信息 message: ${message} from topic: ${topic}`);
                        useUserStore().getMonitoring(phaseValue)
                    } else {
                        // console.log('sssss=======================');
                    }



                });
            }
        } catch (error) {
            console.log("mqtt.connect error:", error);
        }
    };
    // 订阅
    const link = () => {
        let qosValue = qos.value
        console.log(client.value.connected, 'mmmm');
        client.value.subscribe(
            topic.value,
            { qosValue },
            (error, granted) => {
                if (error) {
                    console.log("订阅失败 error:", error);
                    return;
                }
                console.log("订阅成功 successfully:", granted);
            }
        );
    };
    // 取消订阅
    const UnSubscribe = () => {
        let qosValue = qos.value
        client.value.unsubscribe('/decive/pXNqSoCv/push', { qosValue }, (error) => {
            if (error) {
                console.log("取消订阅失败 error:", error);
                return;
            }
            console.log(`取消订阅成功 topic: ${topic}`);
        });
    };
    // 取消连接
    const destroyConnection = () => {
        console.log(client.value.connected, 'ssssssss');
        if (client.value.connected) {
            try {
                client.value.end(false, () => {
                    console.log("断开连接成功 successfully");
                });
            } catch (error) {
                console.log("断开连接失败 error:", error);
            }
        }
    };
    //发送信息  sendMsg //发送的信息
    const SendMessage = (topic, sendMsg) => {
        let qosValue = qos.value
        client.value.publish(this.topic, JSON.stringify(sendMsg), { qosValue }, (err, a) => {
            if (!err) {
                console.log('发送信息成功');
            } else {
                console.log('发送信息失败');
            }
        })
    }

    const retryTimes = ref(0);
    const handleOnReConnect = () => {
        retryTimes.value += 1;
        if (retryTimes.value > 5) {
            try {
                client.value.end();
                initData();
                console.log("connection maxReconnectTimes limit, stop retry");
            } catch (error) {
                console.log("handleOnReConnect catch error:", error);
            }
        }
    };
    const initData = () => {
        client.value = {
            connected: false,
        };
        retryTimes.value = 0;
    };

    return {
        startMqtt,
        link,
        UnSubscribe,
        destroyConnection
    };
}